package net.fpeg.kotlin.msa.wordbase.service

import net.fpeg.kotlin.msa.wordbase.dao.WordSentenceDao
import net.fpeg.kotlin.msa.wordbase.dto.WordSentenceIndexDto
import net.fpeg.kotlin.msa.wordbase.entity.WordSentence
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import javax.transaction.Transactional

@Service
class WordSentenceService {
    @Autowired
    lateinit var wordSentenceDao: WordSentenceDao

    @Autowired
    lateinit var wordSourceService: WordSourceService

    fun save(wordSentences: List<WordSentence>): MutableList<WordSentence> = wordSentenceDao.saveAll(wordSentences)

    private fun get(sentenceId: Long) = wordSentenceDao.getById(sentenceId)

    fun getOne(sentenceId: Long) = get(sentenceId) ?: throw Exception("例句不存在")

    fun find(id: Long, sourceId: Long, pageable: Pageable) = wordSentenceDao.findByWordSource_IdOrderById(sourceId, pageable)
    fun find(id: Long, sourceId: Long) = wordSentenceDao.findByWordSource_IdOrderById(sourceId)

    /**
     * 根据单词和来源id找出所有包含此单词的例句
     */
    fun find(id: Long, sourceId: Long, wordValue: String, pageable: Pageable) =
            wordSentenceDao.findByWordSource_IdInAndEnglishValueContainingOrderById(
                    wordSourceService.findIds(sourceId), wordValue, pageable)


    fun add(id: Long, wordSentenceIndexDto: WordSentenceIndexDto) =
            wordSentenceDao.save(WordSentence(
                    chineseValue = wordSentenceIndexDto.chineseValue,
                    englishValue = wordSentenceIndexDto.englishValue,
                    wordSource = wordSourceService.getOne(wordSentenceIndexDto.wordSourceId)
            ))

    fun edit(id: Long, wordSentenceIndexDto: WordSentenceIndexDto) =
            getOne(wordSentenceIndexDto.wordSentenceId).run {
                englishValue = wordSentenceIndexDto.englishValue
                chineseValue = wordSentenceIndexDto.chineseValue
                wordSource = wordSentenceIndexDto.wordSourceId.let { wordSourceService.getOne(it) }
                wordSentenceDao.save(this)
            }


    @Transactional
    fun remove(id: Long, sentenceId: Long) {
        wordSentenceDao.deleteById(sentenceId)
    }
}